package main

import (
	"ChatServerDemo/protocol"
	"ChatServerDemo/server/utils"
	"bufio"
	"encoding/json"
	"fmt"
	"net"
	"os"
	"time"
)

var nick string = ""
var channel string = ""

func main() {
	conn, err := net.Dial("tcp", "127.0.0.1:8000")
	if err != nil {
		fmt.Println("conn fail...")
	}
	defer conn.Close()
	fmt.Println("connect server successed")

	//给自己取一个昵称吧
	fmt.Printf("Make a nickname:")
	Scanf(&nick)
	fmt.Printf("Join a channel:")
	Scanf(&channel)
	fmt.Println("hello : ", nick, ", welcome to channel ", channel)

	message := protocol.JoinChannel{
		Nick:    nick,
		Channel: channel,
	}
	Send(conn, "JoinChannel", message)

	go Handle(conn)

	var msg string
	for {
		msg = ""
		Scanf(&msg)
		if msg == "./quit" {
			message := protocol.Quit{
				Nick:    nick,
				Channel: channel,
			}
			Send(conn, "Quit", message)
			break
		} else {
			message := protocol.SendMsg{
				Nick:    nick,
				Channel: channel,
				Msg:     msg,
			}
			Send(conn, "SendMsg", message)
		}
	}

}

func Scanf(a *string) {
	reader := bufio.NewReader(os.Stdin)
	data, _, _ := reader.ReadLine()
	*a = string(data)
}

func Send(conn net.Conn, cmd string, msg interface{})  {
	jsonMsg, _ := json.Marshal(msg)
	packet := protocol.TCPPacket{
		Cmd:    cmd,
		Packet: string(jsonMsg),
		Timestamp:  time.Now().Unix(),
	}
	pkg, _ := json.Marshal(packet)
	conn.Write(protocol.Packet(pkg))
}

func Handle(conn net.Conn) {

	for {

		data := make([]byte, 1024)
		msg_read, err := conn.Read(data)
		if msg_read == 0 || err != nil {
			break
		}

		//fmt.Println(string(data[0:msg_read]))

		packet := protocol.TCPPacket{}
		err = json.Unmarshal(data, &packet)

		if err != nil {
			utils.Log("ReceiveMsg[%s] err:%+v", string(data), err)
		}else {
			if packet.Cmd == "Quit" {
				os.Exit(0)
			}

			fmt.Println(packet.Packet)
		}
	}
}